package com.kashow.base;

import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Rect;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.SectionEntity;
import com.kashow.AppContext;
import com.kashow.C;
import com.kashow.R;
import com.kashow.base.adapter.SelectionQuickAdpater;
import com.kashow.Ext;
import com.kashow.network.NetworkDash;
import com.kashow.network.NetworkState;
import com.kashow.network.NetworkStateListener;
import com.kashow.ui.view.EmptyLayout;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public abstract class BaseSelectionFragment<T extends RxBasePresenter, E extends BaseModel, V extends SectionEntity> extends BaseFragment<T, E> implements SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.base_recycler_view)
    public RecyclerView mRecyclerView;

    @BindView(R.id.base_swipe_refresh)
    public SwipeRefreshLayout mSwipeRefresh;

    protected EmptyLayout mEmptyLayout;
    protected List<V> mData = new ArrayList<V>();
    protected SelectionQuickAdpater<V> mAdapter;
    protected boolean isRefreshing;
    protected boolean hasError;

    private BaseSelectionFragment.NetworkChangeListener mNetworkChangeListener;

    class NetworkChangeListener implements NetworkStateListener {

        @Override
        public void onNetworkStateChanged(NetworkState lastState, NetworkState newState) {
            isRefreshing = false;
            Logger.d("lastState----->%s---------newState----->%s---ThreadName---->%s",lastState == null ? "null" : lastState.toString() , newState == null ? "null" : newState.toString(),Thread.currentThread().getName());
            if ((lastState != null && !lastState.isConnected() || lastState == null) && newState.isConnected()) {
                if (mSwipeRefresh != null  && mSwipeRefresh.isRefreshing()) {
                    isRefreshing = false;
                    mSwipeRefresh.setRefreshing(false);
                }
                hideNetWorkError();
                return;
            }

            if (lastState != null && lastState.isConnected() && !newState.isConnected()) {
                if (mSwipeRefresh != null && mSwipeRefresh.isRefreshing()) {
                    isRefreshing = false;
                    mSwipeRefresh.setRefreshing(false);
                }
                showNetWorkError();
            }
        }
    }

    @Override
    public void initEventAndData() {
        mNetworkChangeListener = new NetworkChangeListener();
        NetworkDash.addListener(mNetworkChangeListener);
        initBase();
        initRecyclerView();
    }

    public void initBase() {

    }

    public void initRecyclerView() {
        if (mSwipeRefresh != null) {
            mSwipeRefresh.setOnRefreshListener(this);
            mSwipeRefresh.setColorSchemeResources(R.color.colorBlue);
        }
        mEmptyLayout = new EmptyLayout(getContext());
        mEmptyLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        initAdapter();
        mRecyclerView.setLayoutManager(getLayoutManager());
        mRecyclerView.addItemDecoration(getItemDecoration());
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mAdapter.setEmptyView(mEmptyLayout);
    }


    public RecyclerView.LayoutManager getLayoutManager() {
        return new LinearLayoutManager(getContext(), OrientationHelper.VERTICAL, false);
    }

    public RecyclerView.ItemDecoration getItemDecoration() {
        return new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
            }
        };
    }

    public abstract void initAdapter();

    @Override
    public void onRefresh() {
        if (!AppContext.Utils.g().isAvailable()) {
            mEmptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
        }
    }


    public void showNetWorkError() {
        isRefreshing = false;
        hasError = true;
        mEmptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
        if (mAdapter.getData().isEmpty()) {
            mAdapter.notifyDataSetChanged();
        }
        mEmptyLayout.setListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = null;
                //判断手机系统的版本  即API大于10 就是3.0或以上版本
                if(android.os.Build.VERSION.SDK_INT>10){
                    intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                }else{
                    intent = new Intent();
                    ComponentName component = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");
                    intent.setComponent(component);
                    intent.setAction("android.intent.action.VIEW");
                }
                _mActivity.startActivity(intent);
            }
        });
    }

    public void hideNetWorkError() {
        if (mEmptyLayout.getErrorState() == EmptyLayout.NETWORK_ERROR) {
            mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
            onRefresh();
        }
    }

    protected void onReceiveDataList(List<V> newData) {
        if (mSwipeRefresh != null && isRefreshing) {
            mSwipeRefresh.setRefreshing(false);
            if (newData == null) {
                hasError = true;
                mAdapter.loadMoreFail();
            } else {
                mData = new ArrayList<V>();
                mData.addAll(newData);
                mAdapter.setNewData(mData);
                if (newData.isEmpty()) {
                    mEmptyLayout.setErrorType(EmptyLayout.NO_DATA);
                } if (newData.size() < getPageSize()){
                    mAdapter.setEnableLoadMore(true);
                    mAdapter.loadMoreEnd();
                } else {
                    mAdapter.setEnableLoadMore(true);
                    mAdapter.loadMoreComplete();
                }
            }
            isRefreshing = false;
        } else {
            if (newData == null) {
                hasError = true;
                mAdapter.loadMoreFail();
            } else if (newData.size() < getPageSize()){
                mAdapter.addData(newData);
                mAdapter.loadMoreEnd();
            } else {
                mAdapter.addData(newData);
                mAdapter.loadMoreComplete();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mNetworkChangeListener != null) {
            NetworkDash.removeListener(mNetworkChangeListener);
            mNetworkChangeListener = null;
        }
    }

    public  void onNetworkUnavailable() {
        showNetWorkError();
        if (mSwipeRefresh != null && mSwipeRefresh.isRefreshing()) {
            mSwipeRefresh.post(() -> mSwipeRefresh.setRefreshing(false));
        }
    }


    protected void doRefresh(boolean showRefreshHeader) {
        if (!Ext.g().isAvailable()) {
            onNetworkUnavailable();
            return;
        }
        if (isRefreshing) {
            return;
        }
        isRefreshing = true;
        if (mSwipeRefresh == null) {
            return;
        }
        if (showRefreshHeader && !mSwipeRefresh.isRefreshing()) {
            mSwipeRefresh.post(() -> mSwipeRefresh.setRefreshing(true));
        }
        mAdapter.setEnableLoadMore(false);
        fetchData();
    }

    protected abstract void fetchData();

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_base_list;
    }

    @Override
    protected boolean hasToolbar() {
        return false;
    }

    public int getPageSize() {
        return C.DEFAULT_PAGE_SIZE;
    }
}
